import 'dart:io';
import 'package:extended_image/extended_image.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:wallpaper/components/AlertDialog/my_loading.dart';
import 'package:wallpaper/components/empty.dart';
import 'package:wallpaper/model/options_base.dart';
import 'package:wallpaper/pages/other/local_image_view.dart';

class LocalImage extends StatefulWidget {
  const LocalImage({super.key});

  @override
  LocalImageState createState() => LocalImageState();
}

class LocalImageState extends State<LocalImage> {
  List<String> imageList = []; // 改为列表存储

  Future<void> _pickImageFromGallery() async {
    final List<XFile> images = await ImagePicker().pickMultiImage();
    if (images.isNotEmpty) {
      setState(() {
        imageList.addAll(images.map((image) => image.path).toList());
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        toolbarHeight: 40,
        backgroundColor: Theme.of(context).colorScheme.primaryContainer,
        surfaceTintColor: Theme.of(context).colorScheme.primaryContainer,
        elevation: 0,
        title: Text(
          '本地图片',
          style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
        ),
        actions: [
          IconButton(
              onPressed: () {
                imageList.clear();
                _pickImageFromGallery();
              },
              icon: Icon(Icons.add))
        ],
      ),
      body: imageList.isEmpty
          ? Empty()
          : Padding(
              padding: const EdgeInsets.all(5),
              child: GridView.builder(
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: OptionsBase().imageColumns(context),
                  childAspectRatio: 0.7,
                ),
                itemCount: imageList.length,
                itemBuilder: (context, index) {
                  return buildItem(context, index);
                },
              ),
            ),
    );
  }

  Widget buildItem(context, int index) {
    return Container(
      margin: EdgeInsets.all(OptionsBase().padding / 2),
      decoration: BoxDecoration(
          color: Theme.of(context).colorScheme.surface,
          borderRadius: BorderRadius.circular(10),
          boxShadow: [
            BoxShadow(
              color: Theme.of(context).colorScheme.shadow,
              offset: Offset(1, 2),
              blurRadius: 2,
            ),
          ]),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(10),
        child: GestureDetector(
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                  builder: (context) => LocalImageView(
                        images: imageList,
                        selectedIndex: index,
                      )),
            );
          },
          child: Stack(alignment: Alignment.bottomLeft, children: [
            SizedBox(
                width: double.infinity,
                height: double.infinity,
                child: buildLoad(context, imageList[index])),
          ]),
        ),
      ),
    );
  }

  Widget buildLoad(BuildContext context, String imageUrl) {
    return ExtendedImage.file(
      File(imageUrl),
      width: double.infinity,
      height: double.infinity, // 屏幕高度
      fit: BoxFit.cover,
      mode: ExtendedImageMode.gesture,
      initGestureConfigHandler: (state) {
        return GestureConfig(
          // 缩放最小值
          minScale: 1,
          // 缩放动画最小值 当缩放结束时回到 minScale 值
          animationMinScale: 1,
          // 缩放最大值
          maxScale: 1,
          // 缩放动画最大值 当缩放结束时回到 maxScale 值
          animationMaxScale: 1,
          // 缩放拖拽速度
          speed: 1.0,
          // 拖拽惯性速度
          inertialSpeed: 100.0,
          initialScale: 1.0,
          // 是否使用 ExtendedImageGesturePageView 展示图片
          inPageView: false,
          // 当图片的初始化缩放大于 1.0 的时候，根据相对位置初始化图片
          initialAlignment: InitialAlignment.center,
        );
      },

      /// 加载状态回调
      loadStateChanged: (ExtendedImageState state) {
        switch (state.extendedImageLoadState) {
          /// 加载中
          case LoadState.loading:
            return MyLoading(
              type: 3,
              size: 30,
            );

          /// 加载成功
          case LoadState.completed:
            return state.completedWidget;

          /// 加载失败
          case LoadState.failed:
            // 自己写的加载失败的组件 并且把重试的回调传递过去
            return Center(
              child: Icon(
                Icons.perm_media,
                color: Theme.of(context).colorScheme.primaryContainer,
                size: 50,
              ),
            );
        }
      },
    );
  }
}
